package com.zdb.demo.java.leetcode.q2addtwonumbers;

public class Solution {

    public static void main(String[] args) {
//        [2,4,3]
//        [5,6,4]

        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        
        Solution solution = new Solution();
        ListNode resultNode = solution.addTwoNumbers(l1, l2);
        System.out.println(resultNode);

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int result = getInt(l1) + getInt(l2);

        String str = new StringBuilder(result + "").reverse().toString()   ;
        return strToNode(str);
    }

    public ListNode strToNode(String str) {
        if(str.length() == 0) {
            return null;
        }
        ListNode head = new ListNode(Integer.parseInt(str.substring(0, 1)));
        ListNode tmp1 = head;
        for(int i=1; i<str.length(); i++) {
            ListNode tmp2 = new ListNode(Integer.parseInt(str.substring(i, i+1)));
            tmp1.next = tmp2;
            tmp1 = tmp2;
        }
        return head;
    }

    public int getInt(ListNode l) {
        String s1 = "";
        ListNode tmp = l;
        while(tmp != null) {
            s1 += tmp.val + "";
            tmp = tmp.next;
        }
        return Integer.parseInt(new StringBuilder(s1).reverse().toString());
    }
}



class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
}
